document.addEventListener('DOMContentLoaded', function () {
    // DOM元素
    const fileInput = document.getElementById('file-input');
    const fileSelectBtn = document.getElementById('file-select-btn');
    const dropArea = document.getElementById('drop-area');
    const fileInfo = document.getElementById('file-info');
    const fileName = document.getElementById('file-name');
    const fileSize = document.getElementById('file-size');
    const removeFileBtn = document.getElementById('remove-file');
    const uploadSection = document.getElementById('upload-section');
    const columnSelection = document.getElementById('column-selection');
    const nameColumnSelect = document.getElementById('name-column');
    const startNamingBtn = document.getElementById('start-naming');
    const resultSection = document.getElementById('result-section');
    const nameDisplay = document.getElementById('name-display');
    const rollAgainBtn = document.getElementById('roll-again');
    const exportResultBtn = document.getElementById('export-result');
    const backToUploadBtn = document.getElementById('back-to-upload');
    const historyList = document.getElementById('history-list');
    const themeToggle = document.getElementById('theme-toggle');

    // 数据存储
    let excelData = null;
    let nameList = [];
    let selectedNames = [];

    // 文件选择按钮点击事件
    fileSelectBtn.addEventListener('click', () => {
        fileInput.click();
    });

    // 文件选择事件
    fileInput.addEventListener('change', handleFileSelect);

    // 拖放功能
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, unhighlight, false);
    });

    function highlight() {
        dropArea.classList.add('border-primary');
        dropArea.classList.add('bg-primary/5');
    }

    function unhighlight() {
        dropArea.classList.remove('border-primary');
        dropArea.classList.remove('bg-primary/5');
    }

    dropArea.addEventListener('drop', handleDrop, false);

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const file = dt.files[0];
        if (file) {
            handleFile(file);
        }
    }

    // 处理文件选择
    function handleFileSelect(e) {
        const file = e.target.files[0];
        if (file) {
            handleFile(file);
        }
    }

    // 处理文件
    function handleFile(file) {
        // 检查文件类型
        if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
            alert('请上传Excel文件 (.xlsx 或 .xls)');
            return;
        }

        // 显示文件信息
        fileName.textContent = file.name;
        fileSize.textContent = formatFileSize(file.size);
        fileInfo.classList.remove('hidden');

        // 读取Excel文件
        const reader = new FileReader();
        reader.onload = function (e) {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });

                // 获取第一个工作表
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];

                // 转换为JSON
                excelData = XLSX.utils.sheet_to_json(worksheet);

                if (excelData.length === 0) {
                    alert('Excel文件中没有数据');
                    resetFileSelection();
                    return;
                }

                // 获取列名
                const columnNames = Object.keys(excelData[0]);

                // 清空并添加列选项
                nameColumnSelect.innerHTML = '';
                columnNames.forEach(column => {
                    const option = document.createElement('option');
                    option.value = column;
                    option.textContent = column;
                    nameColumnSelect.appendChild(option);
                });

                // 显示列选择区域
                columnSelection.classList.remove('hidden');

            } catch (error) {
                console.error('Error reading Excel file:', error);
                alert('读取Excel文件时出错，请确保文件格式正确');
                resetFileSelection();
            }
        };
        reader.readAsArrayBuffer(file);
    }

    // 重置文件选择
    function resetFileSelection() {
        fileInput.value = '';
        fileInfo.classList.add('hidden');
        excelData = null;
        nameList = [];
        columnSelection.classList.add('hidden');
        resultSection.classList.add('hidden');
    }

    // 移除文件按钮点击事件
    removeFileBtn.addEventListener('click', resetFileSelection);

    // 开始点名按钮点击事件
    startNamingBtn.addEventListener('click', startNaming);

    // 再抽一次按钮点击事件
    rollAgainBtn.addEventListener('click', startNaming);

    // 返回按钮点击事件
    backToUploadBtn.addEventListener('click', () => {
        resultSection.classList.add('hidden');
        uploadSection.classList.remove('hidden');
        columnSelection.classList.remove('hidden');
    });

    // 导出结果按钮点击事件
    exportResultBtn.addEventListener('click', exportResult);

    // 开始点名
    function startNaming() {
        if (!excelData) return;

        const selectedColumn = nameColumnSelect.value;

        // 提取姓名列表
        nameList = excelData.map(row => row[selectedColumn]).filter(name => name && name.trim() !== '');

        if (nameList.length === 0) {
            alert('所选列中没有有效的姓名数据');
            return;
        }

        // 隐藏上传和列选择区域，显示结果区域
        uploadSection.classList.add('hidden');
        columnSelection.classList.add('hidden');
        resultSection.classList.remove('hidden');

        // 动画效果
        let counter = 0;
        const maxCount = 30; // 动画循环次数
        const interval = 50; // 动画间隔(ms)

        nameDisplay.innerHTML = '<span class="animate-pulse-slow">准备开始...</span>';

        setTimeout(() => {
            const animation = setInterval(() => {
                const randomIndex = Math.floor(Math.random() * nameList.length);
                nameDisplay.textContent = nameList[randomIndex];
                counter++;

                if (counter >= maxCount) {
                    clearInterval(animation);

                    // 最终选择
                    const finalIndex = Math.floor(Math.random() * nameList.length);
                    nameDisplay.textContent = nameList[finalIndex];
                    nameDisplay.classList.add('name-selected');

                    // 添加到历史记录
                    addToHistory(nameList[finalIndex]);

                    // 重置动画类
                    setTimeout(() => {
                        nameDisplay.classList.remove('name-selected');
                    }, 500);
                }
            }, interval);
        }, 500);
    }

    // 添加到历史记录
    function addToHistory(name) {
        const timestamp = new Date().toLocaleTimeString();
        selectedNames.push({ name, timestamp });

        // 更新历史记录UI
        updateHistoryUI();
    }

    // 更新历史记录UI
    function updateHistoryUI() {
        if (selectedNames.length === 0) {
            historyList.innerHTML = `
                <div class="text-center text-gray-400 py-8">
                    <i class="fa fa-clock-o text-3xl mb-2"></i>
                    <p>暂无点名历史</p>
                </div>
            `;
            return;
        }

        historyList.innerHTML = '';

        selectedNames.forEach((item, index) => {
            const historyItem = document.createElement('div');
            historyItem.className = 'flex justify-between items-center p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors';
            historyItem.innerHTML = `
                <div class="flex items-center">
                    <span class="w-6 h-6 bg-primary/10 text-primary rounded-full flex items-center justify-center mr-3 text-sm">${index + 1}</span>
                    <span>${item.name}</span>
                </div>
                <span class="text-xs text-gray-500">${item.timestamp}</span>
            `;
            historyList.appendChild(historyItem);
        });
    }

    // 导出结果
    function exportResult() {
        if (selectedNames.length === 0) {
            alert('没有可导出的点名结果');
            return;
        }

        // 创建工作表
        const ws = XLSX.utils.json_to_sheet(selectedNames);

        // 创建工作簿并添加工作表
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "点名结果");

        // 生成Excel文件并下载
        XLSX.writeFile(wb, `点名结果_${new Date().toISOString().slice(0, 10)}.xlsx`);
    }

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';

        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));

        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 主题切换
    themeToggle.addEventListener('click', () => {
        document.body.classList.toggle('dark-mode');

        const icon = themeToggle.querySelector('i');
        if (icon.classList.contains('fa-moon-o')) {
            icon.classList.remove('fa-moon-o');
            icon.classList.add('fa-sun-o');
        } else {
            icon.classList.remove('fa-sun-o');
            icon.classList.add('fa-moon-o');
        }

        // 这里可以添加深色模式的样式切换逻辑
    });

    // 页面滚动效果
    window.addEventListener('scroll', () => {
        const nav = document.querySelector('nav');
        if (window.scrollY > 10) {
            nav.classList.add('shadow-md');
            nav.classList.remove('shadow-sm');
        } else {
            nav.classList.remove('shadow-md');
            nav.classList.add('shadow-sm');
        }
    });
});  